package com.bryant.bryant_weather.ui.home

import android.content.Context
import android.widget.Toast
import com.bryant.bryant_weather.R
import com.bryant.bryant_weather.base.BasePresenter
import com.bryant.bryant_weather.bean.ChangeCityBean
import com.google.common.reflect.TypeToken
import com.google.gson.Gson
import com.qweather.sdk.response.air.v1.AirV1CurrentResponse
import com.qweather.sdk.response.air.v1.AirV1HourlyResponse
import com.qweather.sdk.response.geo.GeoCityTopResponse
import com.qweather.sdk.response.weather.WeatherHourlyResponse
import com.qweather.sdk.response.weather.WeatherNowResponse

class HomePresenter(val mview: HomeView, val mInteractor: HomeInteractor) :
    BasePresenter<HomeView, HomeInteractor>(mview, mInteractor),
    HomeInteractor.GetWeatherData, HomeInteractor.GetHourlyWeatherData,
    HomeInteractor.GetAirQualityData , HomeInteractor.Get24HourAirQualityData,HomeInteractor.GetCityListData{

    // 定义变量
    private var currShowCityName = ""
    private var currShowCityLongitude = ""
    private var currShowCityLatitude = ""
    private var cityList = arrayListOf<ChangeCityBean>()

    // 设置当前展示的城市名和经纬度 - 由Fragment传递
    fun setCityLocationParams(cityName: String, longitude: String, latitude: String) {
        currShowCityName = cityName
        currShowCityLongitude = longitude
        currShowCityLatitude = latitude
    }

    // ========================== 获取首页天气数据， 在fragment实现 - 用于发送请求， 后传到成功失败方法中
    // this 指向当前对象实例：在 requestMainWeatherData 方法中
    // this 指向当前的 HomePresenter 实例
    /*
    * HomePresenter 实现了 HomeInteractor.GetWeatherData
    * 和 HomeInteractor.GetHourlyWeatherData 接口，
    * this 作为回调接收者传递给 mInteractor 的方法
    * */

    fun requestMainWeatherData() {
        // 1. 获取当前天气数据
        mInteractor.getCityCurrentWeather(
            currShowCityLatitude,
            currShowCityLongitude,
            this
        )
        // 2. 获取24小时天气数据
        mInteractor.getCityHourlyWeather(
            currShowCityLatitude,
            currShowCityLongitude,
            this
        )
        // 3. 获取空气质量数据
        mInteractor.getCurrentAirQualityData(
            currShowCityLatitude,
            currShowCityLongitude,
            this
        )

        // 4. 获取24小时空气质量数据
        mInteractor.get24HourAirQualityData(
            currShowCityLatitude,
            currShowCityLongitude,
            this
        )
    }

    // -----------------------------------------------------

    // ======================================= 请求城市数据 ====================================
    fun requestCityListData() {
        mInteractor.getCityListData(this)
    }
    /**
     * 读取raw中的城市数据
     */
    fun readCitiesFromRaw(context: Context, resId: Int): List<ChangeCityBean> {
        return try {
            // 打开指定的raw资源文件并读取为字符串
            val jsonString = context.resources.openRawResource(resId)
                .bufferedReader()
                .use { it.readText() }

            // 使用TypeToken定义目标类型，用于Gson解析泛型List<ChangeCityBean>
            val type = object : TypeToken<List<ChangeCityBean>>() {}.type

            // 使用Gson将JSON字符串转换为List<ChangeCityBean>对象
           Gson().fromJson(jsonString, type)
        } catch (e: Exception) {
            e.printStackTrace()
            emptyList()
        }
    }
    // -------------------------------------------------------------------------------------


    // ========================= 继承自 HomeInteractor.GetWeatherData 接口 ==================
    override fun getWeatherDataSuccess(response: WeatherNowResponse) {
        mview.getMainWeatherDataSuccess(response)
    }

    override fun getWeatherDataFailed(msg: String) {
        mview.getMainWeatherDataFailed(msg)
    }
// ---------------------------------------------------------------------------------------


    // ========================== 继承自 HomeInteractor.GetHourlyWeatherData 接口 ==================
    // 1. 获取24小时天气成功 - 绑定到 HomeView
    override fun getHourlyWeatherDataSuccess(response: WeatherHourlyResponse) {
        mview.get24HourWeatherDataSuccess(response)
    }

    // 2. 获取24小时天气失败 - 绑定到 HomeView
    override fun getHourlyWeatherDataFailed(msg: String) {
        mview.get24HourWeatherDataFailed(msg)
    }
    // ---------------------------------------------------------------------------------------

    // ========================== 继承自 HomeInteractor.GetAirQualityData 接口 ==================
    override fun getCurrentAirQualitySuccess(response: AirV1CurrentResponse) {
       mview.getAirQualityDataSuccess(response )
    }

    override fun getCurrentAirQualityFailed(msg: String) {
        mview.getAirQualityDataFailed(msg)
    }

    // -----------------------------------------------------------------------------

    // ========================== 继承自 HomeInteractor.Get24HourAirQualityData 接口 ==================
    override fun get24HourAirQualityDataSuccess(response: AirV1HourlyResponse) {
       mview.get24HourAirQualityDataSuccess( response)
    }

    override fun get24HourAirQualityDataFailed(msg: String) {
       mview.get24HourAirQualityDataFailed( msg)
    }
    //------------------------------------------------------------------------------------------


    // ========================== 继承自 HomeInteractor.GetCityListData 接口 ==================
    // 1. 获取城市列表成功 - 绑定到 HomeView
    override fun getCityListSuccess(response: GeoCityTopResponse) {
        // 重置列表，常用于刷新数据- 为MutableList的方法
        cityList.clear()
        //先加当前位置
        var currBean = ChangeCityBean(currShowCityName,  currShowCityLongitude.toDouble(), currShowCityLatitude.toDouble(),true)
        cityList.add(currBean)
        var cityListFromRaw = readCitiesFromRaw(mview.getContext()!!, R.raw.city_list)
        cityListFromRaw.forEach {
            if (it.cityName != currShowCityName) {
                cityList.add(ChangeCityBean(it.cityName, it.latitude, it.longitude, false))
            }
        }

        //这里的数据返回城市/区划都有，数据不够纯净。以及 本地位置和其他城市、区划的排序，正常情况下是服务器处理好，返回给前端
        //和风天气给的城市数据太混乱了，这里不好处理，我们直接拿官方提供的一些城市数据放本地做展示好了
        //        response.topCityList?.forEach {
        //
        //        }
        //刷新列表
        mview.refreshCityList(cityList)
    }

    override fun getCityListFailed(msg: String) {
        Toast.makeText(mview.getContext(), "获取其他城市失败", Toast.LENGTH_SHORT).show()
    }
    // ---------------------------------------------------------------------------------------


}